package com.example.shiwu;


import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.util.ByteUtil;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.SocketInfoUtils;
import com.example.shiwu.util.SocketItemUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ItemInfoActivity extends AppCompatActivity {
    private TextView ItemInfo;
    private ItemsService itemsService;
    private TextView itemName, itemLocation, itemNum, customerName, constructionUnit,
            itmeOperator, itemLine;
    private String itemNameVal, itemLocationVal, itemNumVal, customerNameVal, constructionUnitVal,
            itmeOperatorVal, deviceTypeVal, itemLineVal;
    private Spinner deviceType;
    private Context myContext;
    public TextView title_text, title_seting;
    public ImageView title_back;
    private DeviceService deviceService;
    private SharedPreferences mSharedPreferences;


    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;
    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    private final int DEFAULT_PORT = 8086;
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;
    private int success_count = 0;
    private MyQueue queue;
    private ArrayList<String> msgArray;
    private DataParseUtil dataParseUtil;
    private String itemsId, mas_12_val;
    private SocketItemUtils socketUtils;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_RECEIVE_DATA:
                    break;
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iteminfo);
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_seting = findViewById(R.id.title_setting);
        title_text.setText("创建项目");
        title_seting.setVisibility(View.INVISIBLE);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ItemInfoActivity.this.finish();
            }
        });
        itemsService = new ItemsService();
        ItemInfo = findViewById(R.id.item_btn);
        deviceService = new DeviceService();
        myContext = this;
        queue = new MyQueue();
        msgArray = new ArrayList<String>();
        dataParseUtil = new DataParseUtil();
        deviceService = new DeviceService();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                socketUtils = SocketItemUtils.getInstance();
//                socketListener();
//            }
//        }).start();
        ItemInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSharedPreferences = getSharedPreferences("setting", Context.MODE_PRIVATE);
//                String mBoxAddress = mSharedPreferences.getString("box_add", null);
//                System.out.println("mBoxAddress");
                itemName = findViewById(R.id.item_name_val);
                itemLocation = findViewById(R.id.item_location_val);
                itemNum = findViewById(R.id.item_num_val);
                customerName = findViewById(R.id.customer_name_val);
                constructionUnit = findViewById(R.id.construction_unit_val);
                itmeOperator = findViewById(R.id.itme_operator_val);
                deviceType = findViewById(R.id.device_type_val);
                itemLine = findViewById(R.id.item_line_num_val);
                if (itemName.getText().length() == 0) {
                    Toast.makeText(myContext, "项目名称不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (itemLocation.getText().length() == 0) {
                    Toast.makeText(myContext, "项目地点不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (itemNum.getText().length() == 0) {
                    Toast.makeText(myContext, "项目编号不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (customerName.getText().length() == 0) {
                    Toast.makeText(myContext, "客户目名称不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (constructionUnit.getText().length() == 0) {
                    Toast.makeText(myContext, "施工单位不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (itmeOperator.getText().length() == 0) {
                    Toast.makeText(myContext, "操作人不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (itemLine.getText().length() == 0) {
                    Toast.makeText(myContext, "测线号不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }

                Items items = creatData(itemName, itemLocation, itemNum,
                        customerName, constructionUnit, itmeOperator, deviceType, itemLine);
                boolean bl = itemsService.save(items);
                if (bl) {
                    List<Device> devLis = deviceService.getDevice(new Device());
                    int devId = 0;
                    if(devLis.size()==0){
                        Toast.makeText(myContext, "提交失败，重新进入页面！", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        devId= devLis.get(0).getId();
                        Items items1 = findSelectItem();
                        Device device = new Device();
                        device.setId(devId);
                        device.setItemId(items1.getId().toString());
                        device.setUpdateTime(DateUtils.parseDate());
                        deviceService.updata(device,new Device());
                        Toast.makeText(myContext, "提交成功！", Toast.LENGTH_SHORT).show();
                    }


                    ItemInfoActivity.this.finish();
                    Intent intent = new Intent(ItemInfoActivity.this, ItemInfoListActivity.class);
                    startActivity(intent);

                } else {
                    Toast.makeText(myContext, "提交失败！", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //socketUtils.releaseSocketNew();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }
    public Items creatData(TextView itemName, TextView itemLocation, TextView itemNum, TextView customerName,
                           TextView constructionUnit, TextView itmeOperator, Spinner deviceType, TextView itemLine) {

        itemNameVal = itemName.getText().toString();
        itemLocationVal = itemLocation.getText().toString();
        itemNumVal = itemNum.getText().toString();
        customerNameVal = customerName.getText().toString();
        constructionUnitVal = constructionUnit.getText().toString();
        itmeOperatorVal = itmeOperator.getText().toString();
        deviceTypeVal = deviceType.getSelectedItem().toString();
        itemLineVal = itemLine.getText().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(new Date());
        System.out.println(currentTime);
        List<Items> lis = itemsService.getItems(new Items());
        Items items = null;
        if (lis.size() == 0) {
            items = new Items(itemNameVal, itemLocationVal, itemNumVal,
                    1, customerNameVal, constructionUnitVal, itmeOperatorVal, itemLineVal, deviceTypeVal, currentTime, currentTime);
        } else {
            items = new Items(itemNameVal, itemLocationVal, itemNumVal,
                    0, customerNameVal, constructionUnitVal, itmeOperatorVal, itemLineVal, deviceTypeVal, currentTime, currentTime);
        }

        return items;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:

                finish();

                break;

            default:

                break;

        }

        return super.onOptionsItemSelected(item);
    }

    private void socketListener() {
        socketUtils.startListening();
    }

}
